<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="auto">
      <el-form-item label="SN码（序列号）:" prop="snCode">
        <el-input v-model="queryParams.snCode" placeholder="请输入SN码（序列号）" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="桩编码（ZN码）:" prop="assemblyCode">
        <el-input v-model="queryParams.assemblyCode" placeholder="请输入桩编码（ZN码）" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="售后二维码:" prop="aftersaleCode">
        <el-input v-model="queryParams.aftersaleCode" placeholder="请输入售后二维码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['data:historyProd:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExportTemplate" v-hasPermi="['data:historyProd:export']">导出模版（带*号字段必填）</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['data:historyProd:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['data:historyProd:delete']"
        >删除</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['data:historyProd:export']"
        >导出</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <!-- <el-upload ref="upload" :action="upload.url" accept=".xlsx, .xls" :file-list="fileList"
          :headers="upload.headers" :on-preview="handlePreview" :on-remove="handleRemove" :limit="1"
          :data={threeYardId: this.queryParams.threeYardId } :on-success="handleUploadSuccess"> -->
        <!-- :http-request="handleFileUpload" -->
        <!-- <el-button plain icon="el-icon-download" size="mini" v-hasPermi="['data:historyProd:import']"
            type="primary">文件导入(仅允许导入xls、xlsx格式文件)</el-button>
        </el-upload> -->
        <el-upload ref="upload" :action="upload.url" accept=".xlsx, .xls" :file-list="fileList" :headers="upload.headers" :on-preview="handlePreview" :on-remove="handleRemove" :limit="1" :on-success="handleUploadSuccess">
          <!-- :http-request="handleFileUpload" -->
          <el-button plain icon="el-icon-download" size="mini" v-hasPermi="['data:historyProd:import']" type="primary">文件导入(仅允许导入xls、xlsx格式文件)</el-button>
        </el-upload>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" align="center" width="50" />
      <el-table-column label="SN码（序列号）" align="center" prop="snCode" />
      <el-table-column label="桩编码(ZN码)" align="center" prop="assemblyCode" />
      <el-table-column label="售后二维码" align="center" prop="aftersaleCode" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['data:historyProd:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['data:historyProd:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 新增或者修改 历史产品数据 对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body @opened="snOpen" @closed="resetDetail">
      <el-form ref="form" :model="form" :rules="rules" label-width="130px" :inline="true">
        <el-form-item label="SN码(序列号):" prop="snCode">
          <el-input v-model="form.snCode" placeholder="请输入SN码(序列号)" />
        </el-form-item>
        <el-form-item label="桩编码(ZN码):" prop="assemblyCode">
          <el-input v-model="form.assemblyCode" placeholder="请输入桩编码（ZN码）" />
        </el-form-item>
        <el-form-item label="售后二维码:" prop="aftersaleCode">
          <el-input v-model="form.aftersaleCode" placeholder="请输入售后二维码" />
        </el-form-item>
        <el-form-item label="产品编码:" prop="productCode">
          <el-input v-model="form.productCode" placeholder="请输入产品编码" />
        </el-form-item>
        <el-form-item label="产品名称:" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="产品规格型号:" prop="productSpc">
          <el-input v-model="form.productSpc" placeholder="请输入产品规格型号" />
        </el-form-item>
        <el-form-item label="生产工单编码:" prop="workorderCode">
          <el-input v-model="form.workorderCode" placeholder="请输入生产工单编码" />
        </el-form-item>
      </el-form>
      <div class="yardsContent" v-if="modify">
        <div class="yardsDiv">
          <div>
            <el-button type="success" plain>SN码(序列号)</el-button>
          </div>
          <svg id="jsbarcode1"></svg>
          <!-- <div>SN码（序列号）</div> -->
        </div>
        <div class="yardsDiv">
          <div>
            <el-button type="success" plain>桩编码(ZN码)</el-button>
          </div>
          <div class="qrcode" ref="qrCodeUrl"></div>
          <div class="codetext">{{ form.assemblyCode }}</div>
        </div>
        <div class="yardsDiv">
          <div>
            <el-button type="success" plain>售后码</el-button>
          </div>
          <div class="qrcode" ref="qrCodeUrl1"></div>
          <div class="codetext">{{ form.aftersaleCode }}</div>
        </div>
      </div>
      <el-tabs type="border-card" v-if="modify">
        <el-tab-pane label="物料列表">
          <DataDetails :threeYardId="form.id" :formData="form"></DataDetails>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listProduct,
  getProduct,
  delProduct,
  addProduct,
  updateProduct
} from "@/api/system/product";
import QRCode from "qrcodejs2";
import JsBarcode from "jsbarcode";
import DataDetails from "./item/index.vue";
import { getToken } from "@/utils/auth";
export default {
  name: "Hisdata",
  components: { DataDetails },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【历史产品数据】表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否为修改页面
      modify: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        snCode: null,
        assemblyCode: null,
        aftersaleCode: null
      },
      // 表单参数
      form: {},
      //导入参数
      upload: {
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/mes/pro/product/item/importData"
      },
      fileList: [],
      // 表单校验
      rules: {
        snCode: [{ required: true, message: "SN码（序列号）不能为空", trigger: "blur" }],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询【历史产品数据】列表 */
    getList() {
      //this.loading = false;
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        if (response.code == 200) {
          this.productList = response.rows;
          this.total = response.total;
          this.loading = false;
        } else {
          this.msgError(response.msg);
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.resetDetail()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        snCode: null,
        assemblyCode: null,
        aftersaleCode: null
      };
      this.resetForm("form");
    },
    resetDetail() {
      this.$refs.qrCodeUrl.innerHTML = "";
      this.$refs.qrCodeUrl1.innerHTML = "";
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.queryParams.proHistoryProductItemIdList = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.modify = false;
      this.title = "新增历史产品数据";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(row, "修改的row");
      this.reset();
      const id = row.id || this.ids;
      getProduct(id).then(response => {
        if (response.code == 200) {
          this.form = response.data;
          this.open = true;
          this.modify = true;
          this.title = "修改历史产品数据";
        } else {
          this.msgError(response.msg);
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProduct(this.form).then(response => {
              if (response.code == 200) {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addProduct(this.form).then(response => {
              if (response.code == 200) {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除历史产品数据编号为"' + ids + '"的数据项？')
        .then(function () {
          return delProduct(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },

    // 处理移除操作
    handleRemove(file) {
      console.log(file);
    },
    handlePreview(file) {
      console.log(file);
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code == 200) {
        this.$modal.msgSuccess("上传成功")
        this.getList();
      } else {
        this.$modal.msgSuccess(res.msg)
      }
    },
    /** 导出模版按钮操作 */
    handleExportTemplate() {
      this.download('mes/pro/product/item/exportTemplate', {
        ...this.queryParams
      }, `template${new Date().getTime()}.xlsx`)
    },

    // 导出函数
    handleExport() {
      this.download('mes/pro/product/item/export', {
        ...this.queryParams
      }, `item_${new Date().getTime()}.xlsx`)
    },
    snOpen() {
      console.log(
        document.getElementById("jsbarcode1"),
        this.$refs.qrCodeUrl,
        "====document.getElementById)====="
      );
      this.creatQrCode();
      JsBarcode(document.getElementById("jsbarcode1"), this.form.snCode);
    },
    creatQrCode() {
      var qrcode = new QRCode(this.$refs.qrCodeUrl, {
        text: this.form.assemblyCode, // 需要转换为二维码的内容
        width: 100,
        height: 100,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H
      });
      var qrcode1 = new QRCode(this.$refs.qrCodeUrl1, {
        text: this.form.aftersaleCode, // 需要转换为二维码的内容
        width: 100,
        height: 100,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H
      });
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.yardsContent {
  margin-top: 20px;
  // text-align: center;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;

  div {
    font-size: 18px;
  }
}

.yardsDiv {
  margin: 0 10px;
  display: flex;
  flex-direction: column;
  // justify-content: center;
  align-items: center;
  margin-bottom: 15px;

  button {
    margin-bottom: 10px;
    font-size: 18px;
  }

  .codetext {
    margin-top: 10px;
  }
}
</style>
